<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBackList"
    ></topTitle>
    <div class="mainCon noTitleExplain">
      <el-form
        :model="formData"
        label-width="124px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="信息类型：" prop="type">
              <el-select
                v-model="formData.type"
                filterable
                clearable
                placeholder="请选择"
                @change="changeInfoType"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row class="row-padding-bottom" v-if="isShowReveive">
          <el-col :span="24" class="col-position">
            <el-form-item label="通知对象" prop="reveiveUserType">
              <el-checkbox-group v-model="reveiveUserType">
                <el-checkbox
                  :label="item.code"
                  v-for="(item,index) of reveiveUserTypeList"
                  :key="index"
                >{{item.name}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item
              label="通报范围："
              prop="range"
              style="display: inline-block"
            >
              <el-select
                v-model="formData.range"
                @change="changeRange"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in rangeOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="display: inline-block; margin-left: -110px">
              <el-checkbox v-model="isPublic" @change="handChange"
                >对外公开</el-checkbox
              >
            </el-form-item>
            <el-tooltip content="Top center" placement="top" effect="dark">
              <div slot="content">
                勾选对外公开，未登录的游客也可以在本网站首页看到此信息
              </div>
              <i class="icon iconfont iconhuabanfuben"></i>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item
              label="推送用户："
              prop="pushUsers"
              style="display: inline-block"
            >
              <el-checkbox-group v-model="reveiveUserType">
                <el-checkbox
                  v-for="(item, index) in pushUsersList"
                  :label="item.label"
                  :key="index"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item
              label="重要通知："
              prop="isImportant"
              style="display: inline-block"
            >
              <el-radio-group v-model="formData.isImportant">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom" v-if="formData.isImportant == 1">
          <el-col :span="24" class="col-position">
            <el-form-item label="通知简介：" prop="infoBrief">
              <el-input
                type="textarea"
                v-model="infoBrief"
                maxlength="50"
                show-word-limit
                resize="none"
                placeholder="请输入通知简介，50字符以内"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="来源：" prop="source">
              <el-input
                v-model="formData.source"
                placeholder="请输入来源"
                @blur="formData.source = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="作者：" prop="author">
              <el-input
                v-model="formData.author"
                placeholder="请输入作者"
                @blur="formData.author = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="标题：" prop="title">
              <el-input
                v-model="formData.title"
                placeholder="请输入标题"
                @blur="formData.title = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="内容：" prop="content" class="content">
              <div class="upLoadBox">
                <!-- <el-button class="commonBut saveBtn funComBut" icon="icon iconfont iconshangchuan">
                  <span class="opetareText">上传附件</span>
                </el-button> -->
                <el-button
                  class="uploadImg"
                  icon="icon iconfont iconshangchuan"
                  @click="$refs.upLoadFileRef.clickUpload()"
                >
                  &nbsp;上传</el-button
                >
                <uploadInput
                  class="upLoadDom"
                  :successCallBack="successCallBack"
                  :errorCallBack="errorCallBack"
                  @getData="getData"
                  :uploadUrl="uploadUrl"
                  :upLoadFile="upLoadFile"
                  ref="upLoadFileRef"
                ></uploadInput>
              </div>
              <div class="notice">
                仅支持上传doc、docx、xls、xlsx、txt、rar、zip、jpg、png、pdf格式文件，大小限制{{
                  isCzUser() ? '50M' : '5M'
                }}内，最多5个文件。
              </div>
              <ul class="upLoadFile">
                <li v-for="(item, index) of upLoadFile" :key="index">
                  <i class="el-icon-document links"></i>
                  <span class="name">{{ item.name }}</span>
                  <span class="del" @click="delFile(index)">删除</span>
                </li>
              </ul>
              <!-- 富文本编辑器 -->
              <UE
                :id="id"
                :config="config"
                ref="ue"
                class="ueditorBox"
                v-on:ready="ready"
                v-bind:value="defaultMsg"
                v-on:input="input"
              ></UE>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button
            v-sdc
            class="commonBut saveBtn"
            @click="toPublish('Y')"
            :loading="isAdd"
            v-if="
              (pageType == 'add' &&
                buttonLimitsArr.indexOf('policyNotice:add') > -1) ||
              buttonLimitsArr.indexOf('inforList:add') > -1 ||
              buttonLimitsArr.indexOf('policyNotice:update') > -1 ||
              buttonLimitsArr.indexOf('inforList:update') > -1
            "
            type="primary"
            >发布</el-button
          >
          <el-button
            v-sdc
            class="commonBut saveBtn"
            @click="toSave"
            :loading="isAdd"
            v-if="
              pageType == 'edit' &&
              (buttonLimitsArr.indexOf('policyNotice:update') > -1 ||
                buttonLimitsArr.indexOf('inforList:update') > -1) &&
              !(
                buttonLimitsArr.indexOf('policyNotice:add') > -1 ||
                buttonLimitsArr.indexOf('inforList:add') > -1 ||
                buttonLimitsArr.indexOf('policyNotice:update') > -1 ||
                buttonLimitsArr.indexOf('inforList:update') > -1
              )
            "
            type="primary"
            >发布</el-button
          >
          <el-button
            class="commonBut"
            @click="toPublish('N')"
            v-if="
              buttonLimitsArr.indexOf('policyNotice:add') > -1 ||
              buttonLimitsArr.indexOf('inforList:add') > -1 ||
              buttonLimitsArr.indexOf('policyNotice:update') > -1 ||
              buttonLimitsArr.indexOf('inforList:update') > -1
            "
            >保存草稿</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import UE from '@/components/publicCom/ueditor.vue'
import uploadInput from '@/components/publicCom/uploadInput.vue'

export default {
  name: 'addPunchCardRule',
  data() {
    var checkContent = (rule, value, callback) => {
      var that = this

      setTimeout(function () {
        if (!that.$refs.ue.getUEContent()) {
          return callback(new Error('请添加发布内容'))
        } else {
          callback()
        }
      }, 1000)
    }
    var checkreveiveUserType = (rule, value, callback) => {
      var that = this
      if (that.reveiveUserType.length == 0) {
        return callback(new Error('请选择通知对象'))
      } else {
        callback()
      }
    }
    var checkinfoBrief = (rule, value, callback) => {
      var that = this
      if (!that.infoBrief) {
        return callback(new Error('请输入通知简介'))
      }
      if (that.infoBrief.length > 50) {
        return callback(new Error('最长允许输入50个字'))
      } else {
        callback()
      }
    }
    var checkpushUsers = (rule, value, callback) => {
      var that = this
      if (that.reveiveUserType.length == 0) {
        return callback(new Error('请选择推送用户'))
      } else {
        callback()
      }
    }
    return {
      radio: '',
      checkedCities: [],
      pushUsersList: [
        {
          name: '监察用户',
          label: 'MONITOR',
        },
        {
          name: '行业主管用户',
          label: 'DIRECTOR',
        },
        {
          name: '建设单位用户',
          label: 'OWNER',
        },
        {
          name: '施工总承包用户',
          label: 'CONSTRUCTOR',
        },
        {
          name: '劳务公司',
          label: 'LABOUR',
        },
        {
          name: '项目用户',
          label: 'PROJECT_ADMINISTRATOR',
        },
        {
          name: '银行用户',
          label: 'BANK',
        },
      ],
      back: true,
      show: false,
      titleText: '',
      infoBrief: '',
      formData: {
        type: '',
        reveiveUserType: [],
        source: '',
        isImportant: '',
        infoBrief: '',
        author: '',
        title: '',
        content: '',
        range: '',
        isPublic: '',
        // buttonLimitsArr:this.$store.state.buttonLimitsArr
      },
      buttonLimitsArr: this.$store.state.buttonLimitsArr,
      typeList: [],
      //验证
      formRules: {
        type: [
          {
            required: true,
            message: '请选择信息类型',
            trigger: 'change',
          },
        ],
        reveiveUserType: [
          {
            required: true,
            validator: checkreveiveUserType,
            trigger: 'change',
          },
        ],
        infoBrief: [
          {
            required: true,
            validator: checkinfoBrief,
            trigger: 'change',
          },
        ],
        range: [
          {
            required: true,
            message: '请选择通报范围',
            trigger: 'change',
          },
        ],
        pushUsers: [
          {
            required: true,
            validator: checkpushUsers,
            trigger: 'blur',
          },
        ],
        isImportant: [
          {
            required: true,
            message: '请选择为是否是重要通知',
            trigger: 'change',
          },
        ],
        source: [
          {
            required: true,
            message: '请输入来源',
            trigger: 'blur',
          },
          {
            min: 1,
            max: 50,
            message: '最长允许输入50个字',
            trigger: 'blur',
          },
        ],
        author: [
          {
            required: true,
            message: '请输入作者',
            trigger: 'blur',
          },
          {
            min: 1,
            max: 50,
            message: '最长允许输入50个字',
            trigger: 'blur',
          },
        ],
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur',
          },
          {
            min: 1,
            max: 50,
            message: '最长允许输入50个字',
            trigger: 'blur',
          },
        ],
        content: [
          {
            required: true,
            validator: checkContent,
            trigger: 'blur',
          },
        ],
      },
      // 初始化Ueditor配置参数
      config: {
        initialFrameWidth: null,
        initialFrameHeight: 300,
        autoHeightEnabled: false, //高度自适应
        // wordCount:false, //是否开启字数统计
        enableAutoSave: false, //自动保存功能
        elementPathEnabled: false,
        toolbars: [
          [
            '|',
            'undo',
            'redo',
            '|',
            'bold',
            'italic',
            'underline',
            'fontborder',
            'removeformat',
            'pasteplain',
            '|',
            'forecolor',
            'backcolor',
            'insertorderedlist',
            'insertunorderedlist',
            'cleardoc',
            '|',
            'customstyle',
            'paragraph',
            'fontfamily',
            'fontsize',
            '|',
            'indent',
            '|',
            'justifyleft',
            'justifycenter',
            'justifyright',
            'justifyjustify',
            '|',
            'link',
            'unlink',
            '|',
            'horizontal',
            '|',
            //增加图片上传
            'simpleupload',
            'insertimage',
            '|',
            'preview',
            'searchreplace',
            'drafts',
          ],
        ],
        imageScaleEnabled: false,
      },
      // 不同编辑器必须不同的id
      id: 'container',
      content: '',
      defaultMsg: '', //富文本编辑器初始数据
      upLoadFile: [],
      // 添加loading
      isAdd: false,
      // 保存loading
      isSave: false,
      uploadUrl: 'api-f/files/upload',
      infoId: '',
      pageType: '', //编辑页面还是添加页面
      rangeOptions: [
        { name: '建筑', code: '01' },
        { name: '非建', code: '03' },
        { name: '全部', code: '05' },
      ],
      isPublic: false,
      reveiveUserTypeList: [
        { name: '企业', code: 'COMPANY' },
        { name: '项目', code: 'PROJECT' },
      ],
      reveiveUserType: [],
      isShowReveive: false,
    }
  },
  components: {
    UE,
    uploadInput,
  },
  computed: {},
  created() {
    this.getTypeList()

    this.infoId = this.$route.query.infoId

    if (this.infoId) {
      this.titleText = '编辑信息'
      this.pageType = 'edit'
      this.getInfobyId()
    } else {
      this.titleText = '添加信息'
      this.pageType = 'add'
    }
  },
  mounted() {},
  methods: {
    changeRange(val) {
      this.reveiveUserType = []
      switch (val) {
        case '03':
          this.pushUsersList = [
            { name: '监察用户', label: 'MONITOR' },
            { name: '行业主管用户', label: 'DIRECTOR' },
            { name: '企业用户', label: 'COMPANY' },
            { name: '银行用户', label: 'BANK' },
          ]
          break
        case '05':
          this.pushUsersList = [
            { name: '监察用户', label: 'MONITOR' },
            { name: '行业主管用户', label: 'DIRECTOR' },
            { name: '建设单位用户', label: 'OWNER' },
            { name: '施工总承包用户', label: 'CONSTRUCTOR' },
            { name: '劳务公司', label: 'LABOUR' },
            { name: '项目用户', label: 'PROJECT_ADMINISTRATOR' },
            { name: '企业用户', label: 'COMPANY' },
            { name: '银行用户', label: 'BANK' },
          ]
          break
        default:
          this.pushUsersList = [
            { name: '监察用户', label: 'MONITOR' },
            { name: '行业主管用户', label: 'DIRECTOR' },
            { name: '建设单位用户', label: 'OWNER' },
            { name: '施工总承包用户', label: 'CONSTRUCTOR' },
            { name: '劳务公司', label: 'LABOUR' },
            { name: '项目用户', label: 'PROJECT_ADMINISTRATOR' },
            { name: '银行用户', label: 'BANK' },
          ]
          break
      }
    },
    // 获取类型
    getTypeList() {
      this.axios({
        method: 'post',
        url: 'api-bs/base/dicitem/findbytype',
        data: {
          type: 'INFO_TYPE',
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.typeList = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    changeInfoType(val) {
      //切换清空通知对象
      // this.formData.reveiveUserType = ""
      // this.reveiveUserType = [];
      //信息类型为05（要点）时显示通知对象
      if (val == '05') {
        this.isShowReveive = true
      } else {
        this.isShowReveive = false
      }
    },
    // 点击发布
    toPublish(isPublish) {
      // this.getContent();
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.publish(isPublish)
        } else {
        }
      })
    },
    // 发布
    publish(isPublish) {
      if (isPublish == 'Y') {
        this.isAdd = true
      } else {
        this.isSave = true
      }

      var url = ''
      if (this.pageType == 'edit') {
        url = 'api-i/info/expand/modify'
        this.formData.id = this.infoId
      } else {
        url = 'api-i/info/expand/saveinfo'
      }
      this.formData.fileList = JSON.stringify(this.upLoadFile)
      this.formData.content = this.$refs.ue.getUEContent()
      this.formData.isPublish = isPublish
      this.formData.isPublic = this.isPublic == true ? 1 : 0
      this.formData.reveiveUserType = JSON.stringify(this.reveiveUserType)
      this.formData.infoBrief = this.infoBrief
      this.axios({
        method: 'post',
        url: url,
        data: this.formData,
      })
        .then(
          (response) => {
            var text = ''
            if (isPublish == 'Y') {
              this.isAdd = false
              text = '发布成功'
            } else {
              this.isSave = false
              text = '保存成功'
            }
            if (!response.data.hasError) {
              this.$message({
                message: text,
                type: 'success',
              })
              if (isPublish == 'Y') {
                this.goBack()
              } else {
                this.$router.push('/home/notice/inforList')
                this.$store.commit('GOBACK_NAME', {
                  oldUrl: '/home/notice/inforList',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              }
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'error',
            })
            if (isPublish == 'Y') {
              this.isAdd = false
            } else {
              this.isSave = false
            }
          }
        )
        .catch((error) => {
          if (isPublish == 'Y') {
            this.isAdd = false
          } else {
            this.isSave = false
          }
        })
    },
    // 保存草稿
    saveDraft() {
      this.axios({
        method: 'post',
        url: 'api-i/info/expand/findbyid',
        data: {
          infoId: this.infoId,
        },
      })
        .then(
          (response) => {
            this.isAdd = false
            if (!response.data.hasError) {
              this.$message({
                message: '发布成功',
                type: 'success',
              })
              // this.goBack();
              this.$router.push('/home/notice/inforList')
              this.$store.commit('GOBACK_NAME', {
                oldUrl: '/home/notice/inforList',
                newUrl: this.$router.currentRoute.fullPath,
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'error',
            })
            this.isAdd = false
          }
        )
        .catch((error) => {})
    },
    // 获取之前的数据
    getInfobyId() {
      this.axios({
        method: 'post',
        url: 'api-i/info/expand/findbyid',
        data: {
          infoId: this.infoId,
        },
      })
        .then(
          (response) => {
            this.isAdd = false
            if (!response.data.hasError) {
              this.formData.type = response.data.result.type
              if (this.formData.type == '05') {
                this.isShowReveive = true
                this.reveiveUserType = response.data.result.userTypeList
              } else {
                this.isShowReveive = false
                // this.formData.reveiveUserType = "";
              }
              this.formData.source = response.data.result.source
              this.formData.author = response.data.result.author
              this.formData.title = response.data.result.title
              this.formData.range = response.data.result.range
              this.formData.isPublic = response.data.result.isPublic
              this.isPublic = response.data.result.isPublic == 1 ? true : false
              this.defaultMsg = response.data.result.content

              this.reveiveUserType = response.data.result.userTypeList
              this.formData.isImportant = response.data.result.isImportant
              this.infoBrief = response.data.result.infoBrief

              this.upLoadFile = response.data.result.fileExpandVOs
                ? response.data.result.fileExpandVOs
                : []
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'error',
            })
            this.isAdd = false
          }
        )
        .catch((error) => {})
    },
    toSave() {
      console.log(this.infoBrief)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.save()
        } else {
        }
      })
    },
    handChange(val) {
      this.isPublic = val
    },
    save() {
      this.isAdd = true
      this.formData.content = this.$refs.ue.getUEContent()
      this.formData.id = this.infoId
      this.formData.isPublish = 'Y'
      this.formData.isPublic = this.isPublic == true ? 1 : 0
      this.formData.fileList = JSON.stringify(this.upLoadFile)
      if (this.formData.type == '05') {
        this.formData.reveiveUserType = JSON.stringify(this.reveiveUserType)
      } else {
        this.formData.reveiveUserType = ''
      }
      this.axios({
        method: 'post',
        url: 'api-i/info/expand/modify',
        data: this.formData,
      })
        .then(
          (response) => {
            this.isAdd = false
            if (!response.data.hasError) {
              this.$message({
                message: '发布成功',
                type: 'success',
              })
              this.goBack()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {
            this.$message({
              message: '数据请求失败',
              type: 'error',
            })
            this.isAdd = false
          }
        )
        .catch((error) => {})
    },
    goBack() {
      this.$router.push('/home/notice/inforList')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/notice/inforList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    goBackList() {
      this.$router.push('/home/notice/inforList')
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/notice/inforList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getContent() {
      this.content = this.$refs.ue.getUEContent()
    },
    ready() {
      // 初始化成功
    },
    input(obj) {
      // 编辑器内容有变动，具体处理自行修改
    },
    delFile(index) {
      this.upLoadFile.splice(index, 1)
    },
    // 获取子组件上传成功后的值
    getData(data) {
      this.upLoadFile.push(data)
    },
    successCallBack() {},
    errorCallBack() {},
  },
}
</script>

<style scoped lang="less">
.mainCon /deep/ .ueditorBox {
  line-height: 20px;
}
.mainCon {
  padding: 40px 24px 18px 20px;
}
// 上传附件
.upLoadBox {
  // display: inline-block;
  position: relative;
  .upLoadDom {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    display: none;
    /deep/ #salaryExcelForm {
      line-height: 36px;
      cursor: pointer;
    }
    /deep/ #salaryExcel {
      width: 136px;
      height: 36px;
      cursor: pointer;
    }
  }
}

.notice {
  color: #999;
  font-size: 14px;
  line-height: 14px;
  margin-top: 10px;
  margin-bottom: 12px;
}

// 上传文件
.upLoadFile {
  max-width: 730px;
  margin-bottom: 16px;
  color: #333;
  line-height: 21px;
  li {
    display: inline-block;
    width: 330px;
    margin-right: 20px;
    line-height: 26px;
    margin-bottom: 5px;
    &:hover {
      background-color: #f5f7fa;
      .name {
        color: #409eff;
      }
    }
    .links {
      color: #909399;
      display: inline-block;
      vertical-align: middle;
      font-size: 14px;
      margin-right: 7px;
    }
    .name {
      width: 240px;
      display: inline-block;
      font-size: 14px;
      color: #606266;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      vertical-align: middle;
    }
    .del {
      font-size: 14px;
      color: #409eff;
      margin-left: 20px;
      cursor: pointer;
    }
  }
}

.content /deep/ #container /deep/ .edui-default .edui-editor-breadcrumb {
  display: none;
}
.upLoadDom:hover {
  cursor: pointer;
}

/deep/ .el-form-item__error {
  width: 133px;
}
.uploadImg {
  width: 96px;
  height: 36px;
  color: #009588;
  border: 1px solid #009588;
  line-height: 10px;
}
.btnBox {
  text-align: center;
}
</style>
